package com.gxgeek.rule;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @author gaoxing
 * @create 2018-05-23 下午2:17
 */
@Service
public class GroovyService {
    private GroovyShell shell;

    @PostConstruct
    public void init() {
        shell = new GroovyShell(new Binding());
    }


    public boolean caculateExpress(String express, Map<Long, Boolean> map) {
        String destString = express;
        express = express.trim();
        //express 数字
        for (String ss : express.split("\\D+")) {
            if (map.containsKey(Long.parseLong(ss))) {
                destString = destString.replaceFirst(ss, map.get(Long.parseLong(ss)).toString());
            } else {
                destString = destString.replaceFirst(ss, Boolean.FALSE.toString());
            }
        }

        destString = "return " + destString;

        return (boolean) shell.evaluate(destString);
    }

//    public static void main(String[] args) {
//        String express = " 1 || (2 && 12) && 3";// 规则Id表达式
//        Map<Long, Boolean> map = new HashMap<>();
//        map.put(1L, false);
//        map.put(2L, true);
//        map.put(3L, false);
//        map.put(12L, true);
//
//        GroovyService service = new GroovyService();
//        service.init();
//        System.out.println(service.caculateExpress(express, map));;
//        Binding binding = new Binding();
//
//        GroovyShell shell = new GroovyShell(binding);
//
//
//        System.out.println("_______");
//        for (String ss : express.trim().split("\\D+")) {
//            System.out.println(ss);
//        }
//        System.out.println("----------");
//        String destString = new String(express);
//        for (String ss : express.trim().split("\\D+")) {
//            destString = destString.replaceFirst(ss, map.get(Long.parseLong(ss)).toString());
//        }
//
//        destString = "return " + destString;
//
//        System.out.println(destString);
//        Object value = shell.evaluate(destString);
//        System.out.println(value);
////
////
//    }


}
